<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <meta name="keywords" content="天地图"/>
  <title>天地图－地图API－范例－单个标注点沿直线的轨迹运动</title>

  <style type="text/css">
    body, html{width: 100%;height: 100%;margin:0;font-family:"微软雅黑";}
    #mapDiv{height:70%;width:100%;}
    input,p { margin-top: 10px; margin-left: 5px; font-size: 14px;  }
  </style>
  <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
  <script src="./tdt.api.4.0.0.js"></script>
  <script src="d3.js " charset="utf-8"></script>
  <script type="text/javascript" src="./uni.webview.1.5.4.js"></script>
  <script type="text/javascript" src="D3SvgOverlay.js"></script>
  <script type="text/javascript" src="CarTrack.js"></script>

  <script>
    var map, drivingRoute;
    var zoom = 18;
    var newControl;
    var _CarTrack;
    var carMarker;
    var plan;
    var startIcon = "http://lbs.tianditu.gov.cn/images/bus/start.png";	//起点图标
    var endIcon = "http://lbs.tianditu.gov.cn/images/bus/end.png";		//终点图标
    var carIcon = "http://lbs.tianditu.gov.cn/images/openlibrary/car.png";
    function onLoad() {
      map = new T.Map('mapDiv');
      map.centerAndZoom(new T.LngLat(116.40069, 39.89945), zoom);
      addControl();
      var config = {
        onSearchComplete: searchResult	//检索完成后的回调函数
      };
      drivingRoute = new T.DrivingRoute(map, config);
      drivingRoute.setPolicy(3)
      searchDrivingRoute()
    }
    function  addControl(){
      //允许鼠标滚轮缩放地图
      map.enableScrollWheelZoom();

      newControl = new T.Control({position: T_ANCHOR_BOTTOM_RIGHT});
      newControl.onAdd = function (map) {
        var container = document.createElement("div");
        var zicsstext = "font-size:12px;border:solid 2px blue;background:#fff;padding:2px;line-height:15px;cursor:pointer;";
        var zocsstext = "font-size:12px;border:solid 2px blue;background:#fff;padding:2px;line-height:15px;cursor:pointer;";
        this.zoomInButton = createButton("放大", "放大", 'a', container, zicsstext);
        this.zoomOutButton = createButton("缩小", "缩小", 'b', container, zocsstext);
        this.zoomInButton.onclick = zoomIn;
        this.zoomOutButton.onclick = zoomOut;
        return container;
      };

      newControl.onRemove = function (map) {
        //移除控件时要释放
        delete  this.zoomInButton;
        delete  this.zoomOutButton;
      }

      map.addControl(newControl);
    }
    function zoomIn() {
      map.zoomIn();
    }

    function zoomOut() {
      map.zoomOut();
    }

    function createButton(html, title, className, container, csstext) {
      var link = document.createElement("a");
      if (container) {
        container.appendChild(link);
      }
      link.innerHTML = html;
      link.title = title;
      link.style.cssText = csstext;
      return link;
    }

    function searchDrivingRoute() {
      map.clearOverLays();
      var startLngLat = new T.LngLat(116.354060,39.905650);
      var endLngLat = new T.LngLat(116.369550,39.918690);
      console.log("start=116.354060,39.905650")
      //驾车路线搜索
      drivingRoute.search(startLngLat, endLngLat);
    }

    function createRoute(lnglats, lineColor) {
      _CarTrack = new T.CarTrack(map, {
        interval: 20,
        speed: 1,
        dynamicLine: false,
        Datas: lnglats,
        polylinestyle: {display:false,color: "#2C64A7", width: 5, opacity: 0.9}
      })
    }

    //添加起始点
    function createStartMarker(result) {
     var startMarker = new T.Marker(result.getStart(), {
        icon: new T.Icon({
          iconUrl: startIcon,
          iconSize: new T.Point(44, 34),
          iconAnchor: new T.Point(12, 31)
        })
      });
      map.addOverLay(startMarker);

      var endMarker = new T.Marker(result.getEnd(), {
        icon: new T.Icon({
          iconUrl: endIcon,
          iconSize: new T.Point(44, 34),
          iconAnchor: new T.Point(12, 31)
        })
      });
      map.addOverLay(endMarker);
    }
    function createRoute(lnglats, lineColor) {
      //创建线对象
      var line = new T.Polyline(lnglats, {color: "#2C64A7", weight: 6, opacity: 0.9});
      //向地图上添加线
      map.addOverLay(line);
    }
    function searchResult(result) {
      plan = result.getPlan(0);
      //显示驾车线路
      createRoute(plan.getPath());
      //添加起始点
      createStartMarker(result);
      //获取方案个数
      var routes = result.getNumPlans();
      //绘制方案
      // for (var i = 0; i < routes; i++) {
      //   //获得单条驾车方案结果对象
      //   const plan = result.getPlan(i);
      //   console.log("plan.getPath="+ plan.getPath()[0].lat)
      // }

      //绘制车辆
      var carstyle= {
        display: true,
          iconUrl: "arrow.png",
          width: 35,
          height: 30
      }
      carMarker = new CarOverlay(plan.getPath()[0],carstyle);
      map.addOverLay(carMarker);

      //显示最佳级别
      //map.setViewport(plan.getPath());
    }
    var pos=0;
    function update(){
      if (pos>plan.getPath().length){
        pos=0;
      }
      pos+=1;
      //计算角度
      let rotate = angle(plan.getPath()[pos-1],plan.getPath()[pos]);
      console.log(rotate +"~~经纬度="+JSON.stringify(plan.getPath()[pos-1]))

      carMarker.setLnglat(plan.getPath()[pos-1]);
      carMarker.setRotate(rotate)
    }

    /**
     * 偏转角度
     * @param rotate
     */
    function setRotate (markerImg,rotate) {

      markerImg.style[CSS_TRANSFORM()] = "rotate(" +
        rotate + "deg)";
    }
    /**
     * 每个浏览器的偏转兼容
     * @returns {string}
     * @constructor
     */
    function CSS_TRANSFORM() {
      var div = document.createElement('div');
      var props = [
        'transform',
        'WebkitTransform',
        'MozTransform',
        'OTransform',
        'msTransform'
      ];

      for (var i = 0; i < props.length; i++) {
        var prop = props[i];
        if (div.style[prop] !== undefined) {
          return prop;
        }
      }
      return props[0];
    }
    /**
     * 计算轨迹的距离
     * @returns {number}
     */
    function distance(datas) {
      var d = 0;
      var l = datas.length;
      for (var i = 0; i < l - 1; i++) {
        var p1 = this.dataToLnglat(datas[i]);
        var p2 = this.dataToLnglat(datas[i + 1]);
        d = d + this.map.getDistance(p1, p2);
      }
      return d;
    }

    /**
     *在每个点的真实步骤中设置小车转动的角度
     */
    function angle(curPos, targetPos) {
      var deg = 0;
      if (targetPos.lng != curPos.lng) {
        var tan = (targetPos.lat - curPos.lat) / (targetPos.lng - curPos.lng),
          atan = Math.atan(tan);
        deg = -atan * 360 / (2 * Math.PI);
        if (targetPos.lng < curPos.lng) {
          deg = -deg + 90 + 90;
        } else {
          deg = -deg;
        }
        return -deg;
      } else {
        var disy = targetPos.lat - curPos.lat;
        var bias = 0;
        if (disy > 0)
          bias = -1
        else
          bias = 1
        return (-bias * 90);
      }
    }
    // Converts from degrees to radians.
    function toRadians(degrees) {
      return degrees * Math.PI / 180;
    }

    // Converts from radians to degrees.
    function toDegrees(radians) {
      return radians * 180 / Math.PI;
    }

    function bearing(curPos, targetPos){
      var startLat = toRadians(curPos.lat);
      var startLng = toRadians(curPos.lng);
      var destLat = toRadians(targetPos.lat);
      var destLng = toRadians(targetPos.lng);

      var y = Math.sin(destLng - startLng) * Math.cos(destLat);
      var x = Math.cos(startLat) * Math.sin(destLat) -
        Math.sin(startLat) * Math.cos(destLat) * Math.cos(destLng - startLng);
      var brng = Math.atan2(y, x);
      brng = toDegrees(brng);
      return (brng + 360) % 360;
    }

  </script>
</head>
<body onLoad="onLoad()">
<div id="mapDiv"></div>
<p>本例演示单个标注点沿直线的轨迹运动</p>
<div >
  <input type="button" value="开始" onClick="_CarTrack.start();"/>
  <input type="button" value="暂停" onClick="_CarTrack.pause();"/>
  <input type="button" value="结束" onClick="_CarTrack.stop();"></input>
  <input type="button" value="更新" onClick="update();"></input>
</div>

</body>
</html>
